// https://www.lintcode.com/problem/linked-list-simplification/

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: the linked list to be simplify.
     * @return: return the linked list after simplifiction.
     */
    public ListNode simplify(ListNode head) {
        // write your code here
        if (head != null) {
            ListNode tail = head;
            int size = 1;
            String ssize = "";
            while (tail.next != null) {
                tail = tail.next;
                ++size;
            }
            if (size > 2) {
                ssize = String.valueOf(size - 2);
            }
            ListNode newTail = head;
            for (int i = 0; i < ssize.length(); ++i) {
                Character c = ssize.charAt(i);
                ListNode node = new ListNode(Integer.valueOf(c));
                newTail.next = node;
                newTail = node;
            }
            if (tail != head) {
                newTail.next = tail;
            }
        }
        return head;
    }
}